package com.hbzd.protection.util;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by bingone on 15/12/16.
 */

    import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;


/**
 * 短信http接口的java代码调用示例
 * 基于Apache HttpClient 4.3
 *
 * @author songchao
 * @since 2015-04-03
 */

public class JavaSmsApi {

    //查账户信息的http地址
    private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json";

    //智能匹配模版发送接口的http地址
    private static String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json";

    //模板发送接口的http地址
    private static String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";

    //发送语音验证码接口的http地址
    private static String URI_SEND_VOICE = "https://voice.yunpian.com/v2/voice/send.json";

    //编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";
    
    //apikey
    private static String apikey = "790679815c13ecb354e3c4e9bc8c592f";

    public static void main(String[] args) throws IOException, URISyntaxException {

       /* //修改为您的apikey.apikey可在官网（http://www.yuanpian.com)登录后获取
        String apikey = "790679815c13ecb354e3c4e9bc8c592f";

        //修改为您要发送的手机号
        String mobile = "15222707453";

        *//**************** 查账户信息调用示例 *****************//*
        System.out.println(JavaSmsApi.getUserInfo(apikey));

        *//**************** 使用智能匹配模版接口发短信(推荐) *****************//*
        //设置您要发送的内容(内容必须和某个模板匹配。以下例子匹配的是系统提供的1号模板）
        String text = "【河北中斗】您的验证码是"+random4Char();
        //发短信调用示例
        System.out.println(JavaSmsApi.sendSms(apikey, text, mobile));*/
    	
    	String[] result = sendMessage("15222707453");
    	System.out.println(result);
    }
    /**
     * 
     * @param mobile
     * @param text 4wei
     * @throws IOException 
     */
    public static String[] sendMessage(String mobile) throws IOException{
    	String[] result = new String[2];
    	result[0] = random4Char();
    	String text = "【河北中斗】您的验证码是"+result[0];
    	JSONObject jsonObject = JSONObject.parseObject(JavaSmsApi.sendSms(apikey,text, mobile));
		System.out.println(jsonObject);
		result[1] = jsonObject.getString("msg");
    	return result;
    }
    
    /**
	 * 生成4位随机字符串
	 * @return
	 */
	public static String random4Char(){
		String str = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";  
        String str2[] = str.split(",");//将字符串以,分割  
        int sum = 0;//计数器  
        Random rand = new Random();//创建Random类的对象rand  
        int index = 0;  
        String randStr = "";//创建内容为空字符串对象randStr  
        randStr = "";//清空字符串对象randStr中的值  
        for (int i=0; i<4; ++i)  
        {  
        	index = rand.nextInt(str2.length-1);//在0到str2.length-1生成一个伪随机数赋值给index  
        	randStr += str2[index];//将对应索引的数组与randStr的变量值相连接  
        }  
        System.out.println("验证码：" + randStr);//输出所求的验证码的值  
        return randStr;
	}

    /**
     * 取账户信息
     *
     * @return json格式字符串
     * @throws java.io.IOException
     */

    public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        return post(URI_GET_USER_INFO, params);
    }

    /**
     * 智能匹配模版接口发短信
     *
     * @param apikey apikey
     * @param text   　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public static String sendSms(String apikey, String text, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("text", text);
        params.put("mobile", mobile);
        return post(URI_SEND_SMS, params);
    }

    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
}
